<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryParamsRef"
      :inline="true"
      :model="queryParams"
      label-width="80px"
    >
      <el-form-item label="检验项目" prop="clinicId">
        <el-input
          v-model="queryParams.itemName"
          clearable
          placeholder="请输入检查项目"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验管" prop="labTube">
        <el-select
          v-model="queryParams.labTube"
          clearable
          filterable
          placeholder="请选择检验管"
          style="width: 120px"
        >
          <el-option
            v-for="(item, index) in labTubeList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标本" prop="specimen">
        <el-select
          v-model="queryParams.specimen"
          clearable
          filterable
          placeholder="请选择标本"
          style="width: 110px"
        >
          <el-option
            v-for="dict in dictDataMap['speciman_dict']"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行科室" prop="performedBy">
        <dept-list
          :dept-attribute-str="'4'"
          :dept-id="queryParams.performedBy"
          :org-id="orgId"
          :placeholder="'请选择执行科室'"
          style="width: 120px"
          @deptChange="deptChange($event, '1')"
        />
      </el-form-item>
      <div class="mr20" style="float: right">
        <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-right: 180px">
      <el-col :span="1.5">
        <el-button :align="'center'" plain type="primary" @click="handleAdd"
        >
          <template #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
        <span style="margin-left: 10px; color: #ffab0a"
        >双击表格行可查看检验项目对应的价表明细</span
        >
      </el-col>
    </el-row>
    <el-empty v-if="labVsClinicList.length <= 0" description="暂无数据"></el-empty>
    <el-table
      v-else
      v-adaptive
      :border="true"
      :data="labVsClinicList"
      :header-cell-style="$headerCellStyle"
      :stripe="true"
      highlight-current-row
      @cell-dblclick="cellDblclick"
    >
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="检验类型"
        prop="labId"
        width="80"
      >
        <template #default="scope">
          <template v-for="(item, index) in typeList">
            <span v-if="item.labTypeId === scope.row.labId">{{ item.name }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        :align="'left'"
        :show-overflow-tooltip="true"
        label="检验项目"
        prop="itemName"
        width="180"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="数量"
        prop="amount"
        width="60"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="检验管"
        prop="labTubeLabel"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="标本"
        prop="specimen"
      >
        <template #default="scope">
          <dict-data-tag
            :options="dictDataMap['speciman_dict']"
            :value="scope.row.specimen"
          />
        </template>
      </el-table-column>
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="执行科室"
        prop="deptName"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="排序"
        prop="sort"
      />
      <!--            <el-table-column :show-overflow-tooltip="true" label="创建时间" :align="'center'" prop="createDate"-->
      <!--                             width="180">-->
      <!--                <template #default="scope">-->
      <!--                    <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>-->
      <!--                </template>-->
      <!--            </el-table-column>-->
      <!--            <el-table-column :show-overflow-tooltip="true" label="更新时间" :align="'center'" prop="updateDate"-->
      <!--                             width="180">-->
      <!--                <template #default="scope">-->
      <!--                    <span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>-->
      <!--                </template>-->
      <!--            </el-table-column>-->
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="备注信息"
        prop="remarks"
      />
      <el-table-column
        :align="'center'"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="scope">
          <el-button type="success" @click="handleUpdate(scope.row)"
          >
            <template #icon>
              <i-ep-edit/>
            </template>
            修改
          </el-button>
          <el-button :align="'center'" type="danger" @click="handleDelete(scope.row)"
          >
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改检验项目与诊疗项目对照对话框 -->
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      append-to-body
      width="800px"
      @close="cancel"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="检验类型" prop="labId">
              <el-input v-model="form.typeName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诊疗项目" prop="clinicId">
              <el-input v-if="isShow" v-model="form.itemName"
                        @focus="isShowItemNameFocus()">
              </el-input>
              <automatic-completion
                v-else ref="itemAutomatic"
                v-model="form.itemName" :dict-array="dictArray"
                :table-body-list="tableBodyList"
                :table-head-list="tableHeadList"
                :title="itemTitle"
                style="width: 100%"
                @itemNameInput="itemNameInput"
                @rowClick="rowAutoClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目数量" prop="amount">
              <el-input v-model="form.amount"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验管" prop="labTube">
              <el-select
                v-model="form.labTube"
                filterable
                placeholder="请选择检验管"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in labTubeList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标本" prop="specimen">
              <el-select
                v-model="form.specimen"
                filterable
                placeholder="请选择标本"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['speciman_dict']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行科室" prop="performedBy">
              <dept-list
                :dept-attribute-str="'4'"
                :dept-id="form.performedBy"
                :org-id="orgId"
                :placeholder="'请选择执行科室'"
                style="width: 100%"
                @deptChange="deptChange($event, '2')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-drawer
      v-model="drawer"
      :before-close="handleClose"
      size="43%"
      style="height: 40%; top: calc(100% - 435px); margin-right: 20px"
      title="价表明细"
    >
      <div>
        <price-checked-table
          ref="priceCheckTableRef"
          :clinic-item-info="clinicItemInfo"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {addLabVsClinic, delLabVsClinic, selectPageLabVsClinic, updateLabVsClinic,} from "@/api/base/labVsClinic";
// 项目自动补全组件
import AutomaticCompletion from "@/components/AutomaticCompletion/index.vue";
import {autoBuildQuery} from "@/api/base/clinicItemDict";
import priceCheckedTable from "@/components/PriceCheckedTable/index.vue";
import {useDictStoreHook} from "@/store/modules/dict";
import {clinicTableHeadList, jsonStrInObj} from "@/utils/autoComplete";
import {listSysOrgDict} from "@/api/system/sysOrgDict.ts";

const dictStore = useDictStoreHook();
const priceCheckTableRef = ref();
const itemAutomatic = ref();
const formRef = ref();
const dictDataMap = ref(dictStore.isTypeGetData("speciman_dict"));
// 按钮loading
const buttonLoading = ref(false);
// 价表明细弹出框
const drawer = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 检查项目与诊疗项目对照表格数据
const labVsClinicList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 检查类型list
const typeList = ref<any>([]);
// 点击选中的类别信息
const typeRow = ref<any>({});
// 检验管list
const labTubeList = ref<any>({});
// 查询参数
const queryParamsRef = ref();
const props = defineProps({
  // 机构id
  orgId: {
    type: String,
    default: "",
  },
});
const queryParams = ref<any>({
  itemName: undefined,
  pageNum: 1,
  pageSize: 10,
  orgId: props.orgId,
  labId: undefined,
  clinicId: undefined,
  performedBy: undefined,
  sort: undefined,
  remarks: undefined,
});
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(clinicTableHeadList));
// 项目选择自动补全表格数据
const tableBodyList = ref([]);
// 项目选择自动补全字典数组
const dictArray = ref(["bill_item_class_dict"]);
// 检查项目选择自动补全窗体名称
const itemTitle = ref("检查项目");
// 表单参数
const form = ref<any>({});
// 行点击Row数据
const clinicItemInfo = ref({});
// 表单校验
const rules = ref({
  itemName: [{required: true, message: "诊疗项目不能为空", trigger: "blur"}],
  labId: [{required: true, message: "检查类型不能为空", trigger: "blur"}],
  clinicId: [{required: true, message: "诊疗项目不能为空", trigger: "change"}],
  sort: [{required: true, message: "排序不能为空", trigger: "blur"}],
});


// 查询检验管字典
getLabTubeList();

function init(row, typeListInfo) {
  typeRow.value = row;
  typeList.value = toRaw(typeListInfo);
  queryParams.value.labId = toRaw(row).labTypeId;
  form.value.labId = toRaw(row).labTypeId;
  console.log(form.value)
  getList();
}

/**
 * 查询检验管字典
 */
function getLabTubeList() {
  const params = {
    delFlag: "0",
    dictType: "lab_tube",
    orgId: props.orgId,
  };
  listSysOrgDict(params).then((res) => {
    labTubeList.value = res.data;
  });
}

/** 查询检验项目与诊疗项目对照列表 */
function getList() {
  if (!queryParams.value.labId) {
    return ElMessage.error("请选择检验类别后再查询");
  }
  queryParams.value.delFlag = "0";
  selectPageLabVsClinic(queryParams.value).then((response: any) => {
    labVsClinicList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    vsId: undefined,
    labId: typeRow.value.labTypeId,
    clinicId: undefined,
    itemName: "",
    labTube: undefined,
    specimen: undefined,
    sort: undefined,
    performedBy: undefined,
    delFlag: undefined,
    createBy: undefined,
    updateBy: undefined,
    remarks: undefined,
    amount: 1,
  };
  form.value.typeName = typeRow.value.name;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  queryParams.value.itemName = undefined;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.vsId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.labId) {
    return ElMessage.error("请选择检验类别后再查询");
  }
  reset();
  open.value = true;
  isShow.value = true;
  title.value = "添加检验项目与诊疗项目对照";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  if (!queryParams.value.labId) {
    return ElMessage.error("请选择检验类别后再查询");
  }
  reset();
  form.value = row;
  form.value.typeName = typeRow.value.name;
  open.value = true;
  title.value = "修改检验项目与诊疗项目对照";
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      form.value.orgId = props.orgId;
      buttonLoading.value = true;
      if (form.value.vsId != null) {
        updateLabVsClinic(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            open.value = false;
            isShow.value = true
            form.value.itemName = ""
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addLabVsClinic(form.value)
          .then((_response) => {
            ElMessage.success("新增成功");
            open.value = false;
            isShow.value = true
            form.value.itemName = ""
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsThis = row.vsId || ids.value;
  ElMessageBox.confirm(`是否确认删除检验项目名称为"${row.itemName}"的数据项？`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delLabVsClinic(idsThis).then(() => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {
    });
}

/** 导出按钮操作 */
function handleExport() {
  // this.download('base/labVsClinic/export', {
  //     ...this.queryParams
  // }, `labVsClinic_${new Date().getTime()}.xlsx`)
}

// 执行科室点击事件
function deptChange(obj, type) {
  if (type === "1") {
    queryParams.value.performedBy = obj.deptId;
    getList();
  } else if (type === "2") {
    form.value.performedBy = obj.deptId;
  }
}

function itemNameInput(itemName) {
  if (!itemName) {
    form.value.clinicId = ""
  }
  form.value.itemInfo = itemName;
  getLabListClinicItemDict();
}

/** 自动补全后台查询 */
function getLabListClinicItemDict() {
  // if (form.value.clinicId) {
  let autoForm: any = {};
  autoForm.notInSelect = ["A", "B", "D", "E", "F", "G", "H", "I", "K", "L", "N"];
  // 是否过滤已存在的项目标记
  autoForm.isFiltrationContrastExist = true;
  autoForm.orgId = props.orgId;
  autoForm.itemInfo = form.value.itemInfo;
  autoBuildQuery(autoForm).then((res) => {
    tableBodyList.value = res.data;
    // 打开自动补全弹出框
    itemAutomatic.value.init();
  });
  // } else {
  //   tableBodyList.value = [];
  // }
}

function rowAutoClick(row) {
  itemAutomatic.value.closePopover();
  isShow.value = true
  form.value.clinicId = row.clinicItemId;
  form.value.itemName = row.itemName;
  tableBodyList.value = [];
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.itemName)
    itemAutomatic.value.focusInput()
  })
}

/** 项目选择关闭事件 */
function closePopover() {
  getList();
  tableBodyList.value = [];
}

// 列表行双击事件
function cellDblclick(row) {
  drawer.value = true;
  clinicItemInfo.value = {
    itemCode: row.itemCode,
    itemName: row.itemName,
    clinicItemId: row.clinicId,
  };
}

// 价表明细弹出框关闭事件
function handleClose() {
  drawer.value = false;
}

defineExpose({
  init,
});
</script>
<script lang="ts">
export default {
  name: "LabVsClinic",
};
</script>
<style scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0px;
}
</style>
